package com.ruoyi.quartz.task;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONPath;
import com.doudian.open.api.order_batchDecrypt.OrderBatchDecryptRequest;
import com.doudian.open.api.order_batchDecrypt.OrderBatchDecryptResponse;
import com.doudian.open.api.order_batchDecrypt.data.DecryptInfosItem;
import com.doudian.open.api.order_batchDecrypt.param.CipherInfosItem;
import com.doudian.open.api.order_batchDecrypt.param.OrderBatchDecryptParam;
import com.doudian.open.api.order_orderDetail.OrderOrderDetailRequest;
import com.doudian.open.api.order_orderDetail.OrderOrderDetailResponse;
import com.doudian.open.api.order_orderDetail.data.ShopOrderDetail;
import com.doudian.open.api.order_orderDetail.data.SpecItem;
import com.doudian.open.api.order_orderDetail.param.OrderOrderDetailParam;
import com.doudian.open.core.AccessToken;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.config.DouDianAPI;
import com.ruoyi.system.config.DouDianToken;
import com.ruoyi.system.controller.RxOrderController;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.DouDianMsgDataVo;
import com.ruoyi.system.domain.vo.LiveRecordQueryParam;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IRxBusinessService;
import com.ruoyi.system.utils.IPCheck;
import com.ruoyi.system.utils.JsonToPhp;
import com.ruoyi.system.utils.NumberUtils;
import com.ruoyi.system.utils.node.LabelNote;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.ZonedDateTime;
import java.util.*;

/**
 * 定时任务调度测试
 *
 * @author ruoyi
 */
@Component("douDianMsgScan")
@Slf4j
public class DouDianMsgScan {

    @Autowired
    private RxOrderMapper rxOrderMapper;
    @Autowired
    private RxDoudianMsgMapper rxDoudianMsgMapper;
    @Autowired
    private RxTelMapper rxTelMapper;
    @Autowired
    private RxDoudianAuthorMapper rxDoudianAuthorMapper;
    @Autowired
    private RxDoudianLiveRecordsMapper rxDoudianLiveRecordsMapper;
    @Autowired
    private IRxBusinessService businessService;
    @Autowired
    private RxOrderFollowMapper rxOrderFollowMapper;
    @Autowired
    private DdShuaDanMapper shuaDanMapper;

    @Autowired
    private RxDoudianGoodsMapper doudianGoodsMapper;

    public void scanMsg2() {
        String osName = System.getProperty("os.name").toLowerCase();
        if (osName.contains("win")) {
            log.info("当前操作系统是windows,直接退出定时任务");
            return;
        }
        RxDoudianMsg rxDoudianMsg = new RxDoudianMsg();
        rxDoudianMsg.setStatus(1);
        List<RxDoudianMsg> rxDouDianMsgs = rxDoudianMsgMapper.selectRxDoudianMsgList(rxDoudianMsg);
        if (null != rxDoudianMsg && rxDouDianMsgs.size() > 0) {
            for (RxDoudianMsg r : rxDouDianMsgs) {
                try {
                    switch (r.getTag()) {
                        case "101":
                            tag101(r);
                            break;
                        case "106":
                            tag106(r);
                            break;
                        case "110":
                            tag110(r);
                            break;
                        case "102":
                            tag102(r);
                            break;
                        case "105":
                            tag105(r);
                            break;
                        case "103":
                            tag103(r);
                            break;
                        case "200":
                            tag200(r);
                            break;
                        case "206":
                            tag206(r);
                            break;
                        case "207":
                            tag207(r);
                            break;
                    }
                } catch (Exception e) {
                    log.error("异常:{}", e);
                }
            }
        }
    }


    public void tag110(RxDoudianMsg r) {
        if (!IPCheck.checkIp()) {
            return;
        }
        DouDianMsgDataVo dataVo = JSON.parseObject(JsonToPhp.phpHeadStrToJson(r.getData()), DouDianMsgDataVo.class);
        OrderOrderDetailRequest orderDetailRequest = new OrderOrderDetailRequest();
        OrderOrderDetailParam param2 = orderDetailRequest.getParam();
        param2.setShopOrderId(dataVo.getP_id());
        AccessToken token = DouDianToken.getToken(dataVo.getShop_id());
        OrderOrderDetailResponse response = orderDetailRequest.execute(token);
        if (!"10000".equals(response.getCode())) {
            log.info("查询订单详情-返回,状态不是成功:{}", response);
        }
        String spec3 = "";
        ShopOrderDetail shopOrderDetail = response.getData().getShopOrderDetail();
        List<SpecItem> spec = shopOrderDetail.getSkuOrderList().get(0).getSpec();
        if (null != spec && spec.size() == 3) {
            String sellerTel = NumberUtils.PhoneRemoveSpaces(spec.get(2).getValue());
            spec3 = sellerTel;
            if (sellerTel.length() < 11) {
                Random random = new Random();
                long random10Digit = 1000000000L + (long) (random.nextDouble() * 9000000000L);
                sellerTel = "A" + random10Digit;
            } else if (sellerTel.length() > 11) {
                sellerTel = sellerTel.substring(0, 11);
                if (sellerTel.matches("\\d+")) {
                    spec3 = sellerTel;
                } else {
                    Random random = new Random();
                    long random10Digit = 1000000000L + (long) (random.nextDouble() * 9000000000L);
                    sellerTel = "A" + random10Digit;
                }
            }
            shopOrderDetail.setSellerWords(sellerTel);
        } else {
            DdShuaDan ddShuaDan = new DdShuaDan();
            ddShuaDan.setDouDianOrderId(dataVo.getP_id());
            ddShuaDan.setCreateTime(new Date());
            shuaDanMapper.insertDdShuaDan(ddShuaDan);
            log.info("tag110商品sku配置不对不是3个值,值是:{},直接将当前msg2表状态修改为2,抖店商品id:{}", spec.size(), dataVo.getP_id());
            updateDouDianMsg2Status(r);
            return;
        }
        if (StringUtils.isEmpty(shopOrderDetail.getSellerWords())) {
            throw new RuntimeException("没有查到该号码,商品id:" + dataVo.getP_id());
        }

        RxOrder rxOrder = new RxOrder();
        Map<String, String> map = new HashMap<>();
        OrderBatchDecryptRequest oBDRequest = new OrderBatchDecryptRequest();
        OrderBatchDecryptParam oBDParam = new OrderBatchDecryptParam();
        List<CipherInfosItem> cipherInfosItems = new LinkedList<>();
        CipherInfosItem cipherInfosItem1 = new CipherInfosItem();
        cipherInfosItem1.setAuthId(dataVo.getP_id());
        cipherInfosItem1.setCipherText(shopOrderDetail.getEncryptPostReceiver());
        cipherInfosItems.add(cipherInfosItem1);
        map.put(shopOrderDetail.getEncryptPostReceiver(), "postReceiver");
        CipherInfosItem cipherInfosItem2 = new CipherInfosItem();
        cipherInfosItem2.setAuthId(dataVo.getP_id());
        cipherInfosItem2.setCipherText(shopOrderDetail.getEncryptPostTel());
        cipherInfosItems.add(cipherInfosItem2);
        map.put(shopOrderDetail.getEncryptPostTel(), "postTel");
        CipherInfosItem cipherInfosItem3 = new CipherInfosItem();
        cipherInfosItem3.setAuthId(dataVo.getP_id());
        cipherInfosItem3.setCipherText(shopOrderDetail.getPostAddr().getEncryptDetail());
        cipherInfosItems.add(cipherInfosItem3);
        map.put(shopOrderDetail.getPostAddr().getEncryptDetail(), "addrDetail");
        CipherInfosItem cipherInfosItem4 = new CipherInfosItem();
        cipherInfosItem4.setAuthId(dataVo.getP_id());
        cipherInfosItem4.setCipherText(shopOrderDetail.getUserIdInfo().getEncryptIdCardName());
        cipherInfosItems.add(cipherInfosItem4);
        map.put(shopOrderDetail.getUserIdInfo().getEncryptIdCardName(), "cardName");
        CipherInfosItem cipherInfosItem5 = new CipherInfosItem();
        cipherInfosItem5.setAuthId(dataVo.getP_id());
        cipherInfosItem5.setCipherText(shopOrderDetail.getUserIdInfo().getEncryptIdCardNo());
        cipherInfosItems.add(cipherInfosItem5);
        map.put(shopOrderDetail.getUserIdInfo().getEncryptIdCardNo(), "cardNo");
        oBDParam.setCipherInfos(cipherInfosItems);
        shopOrderDetail.getMaskPostAddr().getProvince();
        shopOrderDetail.getMaskPostReceiver();
        oBDRequest.setParam(oBDParam);
        log.info("{}解密前:{}", dataVo.getP_id(), oBDRequest);
        OrderBatchDecryptResponse oBDResponse = oBDRequest.execute(token);
        log.info("{}解密后:{}", dataVo.getP_id(), oBDResponse);
        List<DecryptInfosItem> decryptInfos = oBDResponse.getData().getDecryptInfos();
        for (DecryptInfosItem decrypt : decryptInfos) {
            String value = map.get(decrypt.getCipherText());
            switch (value) {
                case "postReceiver":
                    rxOrder.setContactname(decrypt.getDecryptText());
                    break;
                case "postTel":
                    rxOrder.setContacttel(decrypt.getDecryptText());
                    rxOrder.setCustomTel(decrypt.getDecryptText());
                    break;
                case "addrDetail":
                    rxOrder.setRealaddress(decrypt.getDecryptText());
                    break;
                case "cardName":
                    rxOrder.setCustomName(decrypt.getDecryptText());
                    break;
                case "cardNo":
                    rxOrder.setCustomNumber(decrypt.getDecryptText());
                    break;
            }
        }
        RxTel rxTel = rxTelMapper.selectRxTelByTelAndState1(shopOrderDetail.getSellerWords());
        rxOrder.setSerial(DateUtils.dateTimeNow() + shopOrderDetail.getSellerWords());
        rxOrder.setOrderprice(NumberUtils.divideBy100(shopOrderDetail.getPayAmount()));
        rxOrder.setState(2);
        rxOrder.setEvidenceChainTag("0");
        rxOrder.setBusinessId(165L);
        rxOrder.setTime(shopOrderDetail.getCreateTime());
        rxOrder.setType(5L);
        rxOrder.setShengId(shopOrderDetail.getPostAddr().getProvince().getName());
        rxOrder.setCityId(shopOrderDetail.getPostAddr().getCity().getName());
        rxOrder.setAreaId(shopOrderDetail.getPostAddr().getTown().getName());
        rxOrder.setStreetId(shopOrderDetail.getPostAddr().getStreet().getName());
        rxOrder.setCustomAddress(rxOrder.getRealaddress());
        rxOrder.setDoudianOrderId(shopOrderDetail.getOrderId());
        if (dataVo.getShop_id().equals("104110047")) {
            rxOrder.setDoudianOrderStatus(10L);
        } else {
            rxOrder.setDoudianOrderStatus(20L);
        }
        rxOrder.setDoudianOrderUserTagUi2(JSON.toJSONString(shopOrderDetail.getUserTagUi()));
        rxOrder.setDoudianOrderPayAmount(NumberUtils.divideBy100(shopOrderDetail.getPayAmount()));
        rxOrder.setDoudianOrderPayTime(shopOrderDetail.getPayTime());
        rxOrder.setDoudianOrderSubBTypeDesc(shopOrderDetail.getSubBTypeDesc());
        rxOrder.setDoudianOrderSpec(JsonToPhp.jsonToPhp(shopOrderDetail.getSkuOrderList().get(0).getSpec().toString()));
        rxOrder.setDoudianOrderShopId(String.valueOf(shopOrderDetail.getShopId()));
        rxOrder.setDoudianOrderShopName(shopOrderDetail.getShopName());
        rxOrder.setDoudianOrderDecryptStstus(String.valueOf(2));
        rxOrder.setDoudianOrderBuyerWords(shopOrderDetail.getBuyerWords());
        if (null != shopOrderDetail.getSkuOrderList().get(0).getAuthorId() && 0 != shopOrderDetail.getSkuOrderList().get(0).getAuthorId()) {
            rxOrder.setDoudianOrderAuthorId(String.valueOf(shopOrderDetail.getSkuOrderList().get(0).getAuthorId()));
            RxDoudianAuthor rxDoudianAuthor = rxDoudianAuthorMapper.selectRxDoudianAuthorByUid(String.valueOf(shopOrderDetail.getSkuOrderList().get(0).getAuthorId()));
            if (null != rxDoudianAuthor) {
                LiveRecordQueryParam param = new LiveRecordQueryParam();
                param.setAuthorId(rxDoudianAuthor.getId());
                param.setTime(shopOrderDetail.getPayTime());
                RxDoudianLiveRecords rxDoudianLiveRecords = rxDoudianLiveRecordsMapper.selectRxDoudianLiveRecordsByAuthorIdAndLiveTime2(param);
                if (null != rxDoudianLiveRecords) {
                    rxOrder.setDoudianOrderManageAuthorId(Long.valueOf(rxDoudianLiveRecords.getManageId()));
                }
            }
        }
        rxOrder.setDoudianOrderProductId(String.valueOf(shopOrderDetail.getSkuOrderList().get(0).getProductId()));
        if (StringUtils.isNotEmpty(rxOrder.getDoudianOrderProductId())) {
            RxDoudianGoods rxDoudianGoods = new RxDoudianGoods();
            rxDoudianGoods.setProductId(rxOrder.getDoudianOrderProductId());
            List<RxDoudianGoods> oldGoods = doudianGoodsMapper.selectRxDoudianGoodsList(rxDoudianGoods);
            if (CollectionUtils.isEmpty(oldGoods)) {
                log.info("商品id:{}在douDian_goods表中没查到数据", rxOrder.getDoudianOrderProductId());
            } else {
                RxDoudianGoods douDianGoods = oldGoods.get(0);
                if (null != douDianGoods && douDianGoods.getIsBroadband() == 2) {
                    ArrayList<LabelNote> hjfLabelNotes = new ArrayList();
                    String value = shopOrderDetail.getSkuOrderList().get(0).getSpec().get(1).getValue();
                    LabelNote labelNote = new LabelNote();
                    labelNote.setType("1");
                    labelNote.setNotes(value);
                    hjfLabelNotes.add(labelNote);
                    String boardBand = JSONArray.toJSONString(hjfLabelNotes);
                    rxOrder.setHjfLabelNotes(boardBand);
                }
            }
        }
        rxOrder.setDoudianXuanhaoTelnumber(shopOrderDetail.getSellerWords());

        if (rxTel != null) {
            rxOrder.setTelId(rxTel.getId());
            rxOrder.setTelnumber(rxTel.getTel());
            rxOrder.setPrice(new BigDecimal(rxTel.getPrice()));
            rxOrder.setBill(new BigDecimal(rxTel.getBill()));
            rxOrder.setClassname(String.valueOf(rxTel.getClassId()));
            rxOrder.setAddteltime(rxTel.getTime());
            rxOrder.setSegmentname(String.valueOf(rxTel.getSegmentId()));
            rxOrder.setSuppliername(String.valueOf(rxTel.getSupplierId()));
            rxOrder.setContent(rxTel.getContent());
            rxOrder.setShengname(rxTel.getShengname());
            rxOrder.setCityname(rxTel.getCityname());
            rxOrder.setUploadfloorprice(BigDecimal.valueOf(rxTel.getUploadfloorprice()));
            RxBusiness business = businessService.selectRxBusinessById(165L);
            RxOrderController.jieSuanJia(rxTel, rxOrder, business);
            RxTel updateTel = new RxTel();
            updateTel.setId(rxTel.getId());
            updateTel.setState(2);
            rxTelMapper.updateRxTel(updateTel);
        }
        if (null == rxTel && spec3.length() == 11) {
            rxOrder.setTelnumber(spec3);
        }
        rxOrderMapper.insertRxOrder(rxOrder);
        if (rxTel != null) {
            RxOrderFollow rxOrderFollow = new RxOrderFollow();
            rxOrderFollow.setTitle("【自动选择订单号码Tag110】");
            rxOrderFollow.setContent("系统将订单号码自动选择为【" + rxTel.getTel() + "】");
            rxOrderFollow.setOrderId(Math.toIntExact(rxOrder.getId()));
            rxOrderFollow.setTime(System.currentTimeMillis() / 1000);
            rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        }

        if (null == rxTel && spec3.length() == 11) {
            RxOrderFollow rxOrderFollow = new RxOrderFollow();
            rxOrderFollow.setTitle("【自动选择订单号码Tag110】");
            rxOrderFollow.setContent("系统将订单号码自动选择为【" + spec3 + "】上架号码中无此号,请知悉.");
            rxOrderFollow.setOrderId(Math.toIntExact(rxOrder.getId()));
            rxOrderFollow.setTime(System.currentTimeMillis() / 1000);
            rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
        }
        if (spec3.length() == 11) {
            DouDianAPI.addOrderRemark(dataVo.getP_id(), spec3, token);
        }
        updateDouDianMsg2Status(r);
    }


    public void tag102(RxDoudianMsg r) {
        String douDianId = JSONPath.eval(JsonToPhp.phpHeadStrToJson(r.getData()), "p_id").toString();
        log.info("抖店已发货-处理自己逻辑:{}", douDianId);
        if (StringUtils.isNotEmpty(douDianId)) {
            RxOrder rxOrder = rxOrderMapper.selectRxOrderByDouDianId(douDianId);
            if (null == rxOrder) {
                DdShuaDan ddShuaDan = shuaDanMapper.selectShuaDanByDouDianOrderId(douDianId);
                if (null != ddShuaDan) {
                    updateDouDianMsg2Status(r);
                    return;
                } else {
                    throw new RuntimeException("rx_order和shua_dan表都没有查到该订单,tag102抖店id:" + douDianId);
                }
            }
            RxOrderFollow rxOrderFollow = new RxOrderFollow();
            rxOrderFollow.setTitle("【抖店已发货Tag102】");
            rxOrderFollow.setContent("抖店侧已发货成功,抖店订单状态进入到已发货状态.");
            rxOrderFollow.setOrderId(Math.toIntExact(rxOrder.getId()));
            rxOrderFollow.setTime(r.getTime());
            rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
            RxOrder rxOrder2 = new RxOrder();
            rxOrder2.setId(rxOrder.getId());
            rxOrder2.setDoudianOrderStatus(30L);
            rxOrderMapper.updateRxOrder(rxOrder2);
            updateDouDianMsg2Status(r);
        } else {
            log.error("tag102消息,没有获取到p_id值:{}", douDianId);
        }
    }


    public void tag103(RxDoudianMsg r) {
        String douDianId = JSONPath.eval(JsonToPhp.phpHeadStrToJson(r.getData()), "p_id").toString();
        log.info("抖店确认收货-已完成-处理自己逻辑:{}", douDianId);
        if (StringUtils.isNotEmpty(douDianId)) {
            RxOrder rxOrder = rxOrderMapper.selectRxOrderByDouDianId(douDianId);
            if (null == rxOrder) {
                DdShuaDan ddShuaDan = shuaDanMapper.selectShuaDanByDouDianOrderId(douDianId);
                if (null != ddShuaDan) {
                    updateDouDianMsg2Status(r);
                    return;
                } else {
                    throw new RuntimeException("rx_order和shua_dan表都没有查到该订单,tag103抖店id:" + douDianId);
                }
            }
            RxOrderFollow rxOrderFollow = new RxOrderFollow();
            rxOrderFollow.setTitle("【抖店已完成Tag103】");
            rxOrderFollow.setContent("抖店侧客户已确认收货.");
            rxOrderFollow.setOrderId(Math.toIntExact(rxOrder.getId()));
            rxOrderFollow.setTime(System.currentTimeMillis() / 1000);
            rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
            RxOrder rxOrder2 = new RxOrder();
            rxOrder2.setId(rxOrder.getId());
            rxOrder2.setDoudianOrderStatus(40L);
            rxOrderMapper.updateRxOrder(rxOrder2);
            updateDouDianMsg2Status(r);
        } else {
            log.error("tag103消息,没有获取到p_id值:{}", douDianId);
        }
    }

    public void tag200(RxDoudianMsg r) {
        String douDianId = JSONPath.eval(JsonToPhp.phpHeadStrToJson(r.getData()), "p_id").toString();
        log.info("抖店待售后-处理自己逻辑:{}", douDianId);
        if (StringUtils.isNotEmpty(douDianId)) {
            RxOrder rxOrder = rxOrderMapper.selectRxOrderByDouDianId(douDianId);
            if (null == rxOrder) {
                DdShuaDan ddShuaDan = shuaDanMapper.selectShuaDanByDouDianOrderId(douDianId);
                if (null != ddShuaDan) {
                    updateDouDianMsg2Status(r);
                    return;
                } else {
                    throw new RuntimeException("rx_order和shua_dan表都没有查到该订单,tag200抖店id:" + douDianId);
                }
            }
            String afterSaleType = JSONPath.eval(JsonToPhp.phpHeadStrToJson(r.getData()), "aftersale_type").toString();
            String reasonCode = JSONPath.eval(JsonToPhp.phpHeadStrToJson(r.getData()), "reason_code").toString();
            log.info("afterSaleType:{},reasonCode:{}", afterSaleType, reasonCode);
            String afterSaleTypeStr = "";
            String reasonCodeStr = "";
            if ("0".equals(afterSaleType)) {
                afterSaleTypeStr = "退货";
            } else if ("1".equals(afterSaleType)) {
                afterSaleTypeStr = "售后仅退款";
            } else if ("2".equals(afterSaleType)) {
                afterSaleTypeStr = "发货前退款";
            } else if ("3".equals(afterSaleType)) {
                afterSaleTypeStr = "换货";
            }
            if ("1".equals(reasonCode)) {
                reasonCodeStr = "多拍/错拍/不想要";
            } else if ("2".equals(reasonCode)) {
                reasonCodeStr = "未按约定时间发货";
            } else if ("105".equals(reasonCode)) {
                reasonCodeStr = "填错地址/电话";
            } else if ("112".equals(reasonCode)) {
                reasonCodeStr = "商品买贵了或降价";
            } else if ("14".equals(reasonCode)) {
                reasonCodeStr = "缺货";
            } else if ("15".equals(reasonCode)) {
                reasonCodeStr = "其它";
            }
            RxOrderFollow rxOrderFollow = new RxOrderFollow();
            rxOrderFollow.setTitle("【抖店待售后Tag200】");
            rxOrderFollow.setContent("抖店侧客户已发起售后申请,请及时联系客户处理. " + afterSaleTypeStr + "原因: " + reasonCodeStr);
            rxOrderFollow.setOrderId(Math.toIntExact(rxOrder.getId()));
            String updateTime = JSONPath.eval(JsonToPhp.phpHeadStrToJson(r.getData()), "update_time").toString();
            if (StringUtils.isNotEmpty(updateTime)) {
                ZonedDateTime zonedDateTime = ZonedDateTime.parse(updateTime);
                long epochSecond = zonedDateTime.toInstant().getEpochSecond();
                rxOrderFollow.setTime(epochSecond);
            } else {
                rxOrderFollow.setTime(System.currentTimeMillis() / 1000);
            }
            rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
            RxOrder rxOrder2 = new RxOrder();
            rxOrder2.setId(rxOrder.getId());
            if (null != rxOrder && (rxOrder.getState() == 6 || rxOrder.getState() == 7 || rxOrder.getState() == 8 || rxOrder.getState() == 100)) {
            } else {
                rxOrder2.setEmergentStatus(2L);
            }
            rxOrder2.setDoudianOrderStatus(50L);
            rxOrder2.setDoudianOrderAftersaleType(Long.valueOf(afterSaleType));
            rxOrder2.setDoudianOrderReasonCode(Long.valueOf(reasonCode));
            rxOrderMapper.updateRxOrder(rxOrder2);
            updateDouDianMsg2Status(r);
        }
    }


    public void tag106(RxDoudianMsg r) {
        String douDianId = JSONPath.eval(JsonToPhp.phpHeadStrToJson(r.getData()), "p_id").toString();
        log.info("抖店还未审核的订单,用户就0取消订单:{}", douDianId);
        if (StringUtils.isNotEmpty(douDianId)) {
            RxOrder rxOrder = rxOrderMapper.selectRxOrderByDouDianId(douDianId);
            if (null == rxOrder) {
                DdShuaDan ddShuaDan = shuaDanMapper.selectShuaDanByDouDianOrderId(douDianId);
                if (null != ddShuaDan) {
                    updateDouDianMsg2Status(r);
                    return;
                } else {
                    updateDouDianMsg2Status(r);
                    throw new RuntimeException("rx_order和shua_dan表都没有查到该订单,tag106抖店id:" + douDianId);
                }
            }
            RxOrderFollow rxOrderFollow = new RxOrderFollow();
            rxOrderFollow.setTitle("【抖店已退款(审核前被退款)Tag106】");
            rxOrderFollow.setContent("店侧客户已退款成功,订单已关闭,请及时联系客户处理.");
            rxOrderFollow.setOrderId(Math.toIntExact(rxOrder.getId()));
            String cancel_time = JSONPath.eval(JsonToPhp.phpHeadStrToJson(r.getData()), "cancel_time").toString();
            if (StringUtils.isNotEmpty(cancel_time)) {
                rxOrderFollow.setTime(Long.valueOf(cancel_time));
            } else {
                rxOrderFollow.setTime(System.currentTimeMillis() / 1000);
            }
            rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
            RxOrder rxOrder2 = new RxOrder();
            rxOrder2.setId(rxOrder.getId());
            if (null != rxOrder && (rxOrder.getState() == 6 || rxOrder.getState() == 7 || rxOrder.getState() == 8 || rxOrder.getState() == 100)) {
            } else {
                rxOrder2.setEmergentStatus(2L);
            }
            RxOrderFollow queryOrderFollow = new RxOrderFollow();
            queryOrderFollow.setOrderId(rxOrder.getId().intValue());
            List<RxOrderFollow> rxOrderFollows = rxOrderFollowMapper.selectRxOrderFollowList(queryOrderFollow);
            if (null != rxOrderFollows) {
                rxOrder2.setDoudianOrderStatus(70L);
            }
            rxOrderMapper.updateRxOrder(rxOrder2);
            updateDouDianMsg2Status(r);
        }
    }

    public void tag206(RxDoudianMsg r) {
        String douDianId = JSONPath.eval(JsonToPhp.phpHeadStrToJson(r.getData()), "p_id").toString();
        log.info("抖店审核后的订单时用户取消订单:{}", douDianId);
        if (StringUtils.isNotEmpty(douDianId)) {
            RxOrder rxOrder = rxOrderMapper.selectRxOrderByDouDianId(douDianId);
            if (null == rxOrder) {
                DdShuaDan ddShuaDan = shuaDanMapper.selectShuaDanByDouDianOrderId(douDianId);
                if (null != ddShuaDan) {
                    updateDouDianMsg2Status(r);
                    return;
                } else {
                    throw new RuntimeException("rx_order和shua_dan表都没有查到该订单,tag206抖店id:" + douDianId);
                }
            }
            RxOrderFollow rxOrderFollow = new RxOrderFollow();
            rxOrderFollow.setTitle("【抖店已退款(审核后被退款)Tag206】");
            rxOrderFollow.setContent("抖店侧客户已退款成功,订单已关闭,请及时联系客户处理.");
            rxOrderFollow.setOrderId(Math.toIntExact(rxOrder.getId()));
            String updateTime = JSONPath.eval(JsonToPhp.phpHeadStrToJson(r.getData()), "update_time").toString();
            if (StringUtils.isNotEmpty(updateTime)) {
                ZonedDateTime zonedDateTime = ZonedDateTime.parse(updateTime);
                long epochSecond = zonedDateTime.toInstant().getEpochSecond();
                rxOrderFollow.setTime(epochSecond);
            } else {
                rxOrderFollow.setTime(System.currentTimeMillis() / 1000);
            }
            rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
            RxOrder rxOrder2 = new RxOrder();
            rxOrder2.setId(rxOrder.getId());
            if (null != rxOrder && (rxOrder.getState() == 6 || rxOrder.getState() == 7 || rxOrder.getState() == 8 || rxOrder.getState() == 100)) {
            } else {
                rxOrder2.setEmergentStatus(2L);
            }
            RxOrderFollow queryOrderFollow = new RxOrderFollow();
            queryOrderFollow.setOrderId(rxOrder.getId().intValue());
            List<RxOrderFollow> rxOrderFollows = rxOrderFollowMapper.selectRxOrderFollowList(queryOrderFollow);
            if (null != rxOrderFollows) {
                if (rxOrderFollows.stream().anyMatch(old -> "审核失败".equals(old.getTitle()))) {
                    rxOrder2.setDoudianOrderStatus(60L);
                } else {
                    rxOrder2.setDoudianOrderStatus(70L);
                }
            } else {
                rxOrder2.setDoudianOrderStatus(70L);
            }
            rxOrderMapper.updateRxOrder(rxOrder2);
            updateDouDianMsg2Status(r);
        }
    }


    public void tag207(RxDoudianMsg r) {
        String douDianId = JSONPath.eval(JsonToPhp.phpHeadStrToJson(r.getData()), "p_id").toString();
        log.info("抖店取消售后-处理自己逻辑:{}", douDianId);
        if (StringUtils.isNotEmpty(douDianId)) {
            DdShuaDan ddShuaDan = shuaDanMapper.selectShuaDanByDouDianOrderId(douDianId);
            if (null != ddShuaDan) {
                updateDouDianMsg2Status(r);
                return;
            }
            RxOrder rxOrder = rxOrderMapper.selectRxOrderByDouDianId(douDianId);
            if (null == rxOrder) {
                throw new RuntimeException("rx_order和shua_dan表都没有查到该订单,tag207抖店id:" + douDianId);
            }
            RxOrder rxOrder2 = new RxOrder();
            OrderOrderDetailRequest orderDetailRequest = new OrderOrderDetailRequest();
            OrderOrderDetailParam param = orderDetailRequest.getParam();
            param.setShopOrderId(douDianId);
            AccessToken token = DouDianToken.getToken(rxOrder.getDoudianOrderShopId());
            OrderOrderDetailResponse response = orderDetailRequest.execute(token);
            if (!"10000".equals(response.getCode())) {
                log.info("查询订单详情-返回,状态不是成功:{}", response);
            }
            ShopOrderDetail shopOrderDetail = response.getData().getShopOrderDetail();
            if (null != shopOrderDetail) {
                if (3L == shopOrderDetail.getOrderStatus()) {
                    rxOrder2.setDoudianOrderStatus(30L);
                } else if (105L == shopOrderDetail.getOrderStatus()) {
                    rxOrder2.setDoudianOrderStatus(20L);
                } else if (5L == shopOrderDetail.getOrderStatus()) {
                    rxOrder2.setDoudianOrderStatus(40L);
                }
            }
            rxOrder2.setEmergentStatus(1L);
            rxOrder2.setId(rxOrder.getId());
            rxOrderMapper.updateRxOrder(rxOrder2);
            RxOrderFollow rxOrderFollow = new RxOrderFollow();
            rxOrderFollow.setTitle("【抖店取消售后Tag207】");
            rxOrderFollow.setContent("抖店侧客户已取消售后申请,请知悉.");
            rxOrderFollow.setOrderId(Math.toIntExact(rxOrder.getId()));
            rxOrderFollow.setTime(System.currentTimeMillis() / 1000);
            rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
            updateDouDianMsg2Status(r);
        }
    }


    public void tag101(RxDoudianMsg r) {
        DouDianMsgDataVo dataVo = JSON.parseObject(JsonToPhp.phpHeadStrToJson(r.getData()), DouDianMsgDataVo.class);
        String douDianId = dataVo.getP_id();
        log.info("抖店状态变为待发货通知:{}", douDianId);
        if (StringUtils.isNotEmpty(douDianId)) {
            if ("53".equals(dataVo.getBiz())) {
                RxOrder oldRxOrder = rxOrderMapper.selectRxOrderByDouDianId(douDianId);
                if (oldRxOrder.getDoudianOrderStatus() == 30L) {
                    updateDouDianMsg2Status(r);
                    return;
                }
                if (null != oldRxOrder) {
                    RxOrder newRxOrder = new RxOrder();
                    newRxOrder.setId(oldRxOrder.getId());
                    newRxOrder.setEmergentStatus(1L);
                    newRxOrder.setDoudianOrderStatus(20L);
                    rxOrderMapper.updateRxOrder(newRxOrder);
                    updateDouDianMsg2Status(r);
                    RxOrderFollow rxOrderFollow = new RxOrderFollow();
                    rxOrderFollow.setTitle("【已过审待发货Tag101】");
                    rxOrderFollow.setContent("订单审核已通过,抖店订单状态进入到待发货状态.");
                    rxOrderFollow.setOrderId(Math.toIntExact(oldRxOrder.getId()));
                    rxOrderFollow.setTime(r.getTime());
                    rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
                }
            }
        } else {
            log.error("tag101消息,没有获取到p_id值:{}", douDianId);
        }
    }


    public void tag105(RxDoudianMsg r) {
        if (!IPCheck.checkIp()) {
            return;
        }
        RxOrder rxOrder2 = new RxOrder();
        JSONObject root = JSON.parseObject(JsonToPhp.phpHeadStrToJson(r.getData()));
        String douDianId = root.getString("p_id");
        log.info("抖店改地址-处理自己逻辑:{}", douDianId);
        if (StringUtils.isNotEmpty(douDianId)) {
            RxOrder rxOrder = rxOrderMapper.selectRxOrderByDouDianId(douDianId);
            if (null == rxOrder) {
                DdShuaDan ddShuaDan = shuaDanMapper.selectShuaDanByDouDianOrderId(douDianId);
                if (null != ddShuaDan) {
                    log.info("tag105消息在shua_dian表中查到了数据,直接将当前msg2表状态修改为2.抖店id:{}", douDianId);
                    updateDouDianMsg2Status(r);
                    return;
                } else {
                    throw new RuntimeException("rx_order和shua_dan表都没有查到该订单,tag105抖店id:" + douDianId);
                }
            }
            JSONObject receiverMsg = root.getJSONObject("receiver_msg");
            JSONObject addr = JSON.parseObject(receiverMsg.getString("addr"));
            String province = addr.getJSONObject("province").getString("name");
            String city = addr.getJSONObject("city").getString("name");
            String town = addr.getJSONObject("town").getString("name");
            String street = addr.getJSONObject("street").getString("name");
            String detail = addr.getString("encrypt_detail");
            String name = receiverMsg.getString("encrypt_name");
            String tel = receiverMsg.getString("encrypt_tel");
            log.info("抖店修改地址抖店id:{},省:{},市:{},区:{},街道:{},详细:{},联系人:{},电话:{}", douDianId, province, city, town, street, detail, name, tel);
            Map<String, String> map = new HashMap<>();
            OrderBatchDecryptRequest oBDRequest = new OrderBatchDecryptRequest();
            OrderBatchDecryptParam oBDParam = new OrderBatchDecryptParam();
            List<CipherInfosItem> cipherInfosItems = new LinkedList<>();
            CipherInfosItem cipherInfosItem1 = new CipherInfosItem();
            cipherInfosItem1.setAuthId(douDianId);
            cipherInfosItem1.setCipherText(detail);
            map.put(detail, "detail");
            cipherInfosItems.add(cipherInfosItem1);
            CipherInfosItem cipherInfosItem2 = new CipherInfosItem();
            cipherInfosItem2.setAuthId(douDianId);
            cipherInfosItem2.setCipherText(name);
            map.put(name, "name");
            cipherInfosItems.add(cipherInfosItem2);
            CipherInfosItem cipherInfosItem3 = new CipherInfosItem();
            cipherInfosItem3.setAuthId(douDianId);
            cipherInfosItem3.setCipherText(tel);
            map.put(tel, "tel");
            cipherInfosItems.add(cipherInfosItem3);
            oBDParam.setCipherInfos(cipherInfosItems);
            oBDRequest.setParam(oBDParam);
            AccessToken token = DouDianToken.getToken(rxOrder.getDoudianOrderShopId());
            OrderBatchDecryptResponse oBDResponse = oBDRequest.execute(token);
            log.info("用户敏感信息解密后:{}", oBDResponse);
            List<DecryptInfosItem> decryptInfos = oBDResponse.getData().getDecryptInfos();
            for (DecryptInfosItem decrypt : decryptInfos) {
                String value = map.get(decrypt.getCipherText());
                switch (value) {
                    case "name":
                        rxOrder2.setContactname(decrypt.getDecryptText());
                        break;
                    case "tel":
                        rxOrder2.setContacttel(decrypt.getDecryptText());
                        rxOrder2.setCustomTel(decrypt.getDecryptText());
                        break;
                    case "detail":
                        rxOrder2.setRealaddress(decrypt.getDecryptText());
                        rxOrder2.setCustomAddress(detail);
                        break;
                }
            }
            rxOrder2.setShengId(province);
            rxOrder2.setCityId(city);
            rxOrder2.setAreaId(town);
            rxOrder2.setStreetId(street);
            rxOrder2.setId(rxOrder.getId());
            rxOrder2.setEmergentStatus(2L);
            rxOrderMapper.updateRxOrder(rxOrder2);
            RxOrderFollow rxOrderFollow = new RxOrderFollow();
            rxOrderFollow.setTitle("【抖店改地址Tag105】");
            rxOrderFollow.setContent("抖店侧客户已将收货人由【" + rxOrder.getContactname() + "】改为【" + rxOrder2.getContactname() + "】;联系电话由【" +
                    rxOrder.getContacttel() + "】 改为【" + rxOrder2.getContacttel() + "】;收货地址由【" +
                    rxOrder.getShengId() + rxOrder.getCityId() + rxOrder.getAreaId() + rxOrder.getStreetId() + rxOrder.getRealaddress()
                    + "】改为【" + rxOrder2.getShengId() + rxOrder2.getCityId() + rxOrder2.getAreaId() + rxOrder2.getStreetId() + rxOrder2.getRealaddress() + "】请及时联系客户处理.");
            rxOrderFollow.setOrderId(Math.toIntExact(rxOrder.getId()));
            rxOrderFollow.setTime(System.currentTimeMillis() / 1000);
            rxOrderFollowMapper.insertRxOrderFollow(rxOrderFollow);
            updateDouDianMsg2Status(r);
        }
    }


    private void updateDouDianMsg2Status(RxDoudianMsg r) {
        RxDoudianMsg rxDoudianMsg = new RxDoudianMsg();
        rxDoudianMsg.setId(r.getId());
        rxDoudianMsg.setStatus(2);
        rxDoudianMsgMapper.updateRxDoudianMsg(rxDoudianMsg);
    }

}
